package cn.iocoder.yudao.module.erp.service.dp;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.common.DpCountQuantity;
import cn.iocoder.yudao.module.erp.controller.admin.dp.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.dispatchvehicle.DispatchVehicleDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dp.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.dpitem.DpItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dplist.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.bankstatement.BankStatementDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.claim.ClaimDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.pay.PayDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.gi.*;
import cn.iocoder.yudao.module.erp.dal.mysql.dispatchvehicle.DispatchVehicleMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.dp.*;
import cn.iocoder.yudao.module.erp.dal.mysql.dpeast.*;
import cn.iocoder.yudao.module.erp.dal.mysql.dpitem.DpItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.dpwest.*;
import cn.iocoder.yudao.module.erp.dal.mysql.finance.bankstatement.BankStatementMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.finance.claim.ClaimMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.finance.pay.PayMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.gi.*;
import cn.iocoder.yudao.module.erp.service.gi.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.DPIDS_IMPORT_LIST_IS_EMPTY;

/**
 * ERP总制单 Service 实现类
 * @author 天使管理员
 */
@Service
@Validated
public class DpServiceImpl implements DpService {

    @Resource
    private DpMapper dpMapper;
    @Resource
    private DpDnMapper dpDnMapper;
    @Resource
    private DpGzMapper dpGzMapper;
    @Resource
    private DpWlmqMapper dpWlmqMapper;
    @Resource
    private DpYwMapper dpYwMapper;
    @Resource
    private DpEastListMapper dpEastListMapper;
    @Resource
    private DpWestListMapper dpWestListMapper;
    @Resource
    private DpItemMapper dpItemMapper;
    @Resource
    private DispatchVehicleMapper dispatchVehicleMapper;
    @Resource
    private DpNjMapper dpNjMapper;
    @Resource
    private DpBjMapper dpBjMapper;
    @Resource
    private DpDxMapper dpDxMapper;
    @Resource
    private PayMapper payMapper;
    @Resource
    private ClaimMapper claimMapper;
    @Resource
    private DpAlmtMapper dpAlmtMapper;
    @Resource
    private DpBiskMapper dpBiskMapper;
    @Resource
    private DpWslMapper dpWslMapper;
    @Resource
    private DpMskMapper dpMskMapper;
    @Resource
    private DpSignMapper dpSignMapper;

    @Lazy
    @Resource
    private GiYwServiceImpl giYwService;
    @Lazy
    @Resource
    private GiGzServiceImpl giGzService;
    @Lazy
    @Resource
    private GiDnServiceImpl giDnService;
    @Lazy
    @Resource
    private GiWlmqServiceImpl giWlmqService;
    @Lazy
    @Resource
    private GiNjServiceImpl giNjService;
    @Lazy
    @Resource
    private GiBjServiceImpl giBjService;
    @Lazy
    @Resource
    private GiDxServiceImpl giDxService;
    @Resource
    private GiYwMapper giYwMapper;
    @Resource
    private GiGzMapper giGzMapper;
    @Resource
    private GiDxMapper giDxMapper;
    @Resource
    private GiDnMapper giDnMapper;
    @Resource
    private GiNjMapper giNjMapper;
    @Resource
    private GiBjMapper giBjMapper;
    @Resource
    private GiWlmqMapper giWlmqMapper;
    @Resource
    private BankStatementMapper bankStatementMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createDp(DpSaveReqVO createReqVO) {
        // 插入
        DpDO dp = BeanUtils.toBean(createReqVO, DpDO.class);
        dpMapper.insert(dp);
        // 插入子表
        createDpEastList(dp.getId(), createReqVO.getDpEastLists());
        createDpWestList(dp.getId(), createReqVO.getDpWestLists());
        createDpItemList(dp.getId(), createReqVO.getDpItems());
        // 返回
        return dp.getId();
    }

    private void createDpEastList(String no, List<DpEastListDO> list) {
        if (list == null || list.size() == 0){
            return;
        }
        list.forEach(o -> o.setNo(no));
        dpEastListMapper.insertBatch(list);
    }

    private void createDpWestList(String no, List<DpWestListDO> list) {
        if (list == null || list.size() == 0){
            return;
        }
        list.forEach(o -> o.setNo(no));
        dpWestListMapper.insertBatch(list);
    }

    private void createDpItemList(String no, List<DpItemDO> list) {
        if (list == null || list.size() == 0){
            return;
        }
        list.forEach(o -> o.setNo(no));
        dpItemMapper.insertBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDp(DpSaveReqVO updateReqVO) {
        String id = updateReqVO.getId();
        // 更新
        DpDO updateObj = BeanUtils.toBean(updateReqVO, DpDO.class);
        updateObj.setRemCount(updateReqVO.getInCount());
        updateObj.setRemVolume(updateReqVO.getInVolume());
        updateObj.setRemWeight(updateReqVO.getWeight());
        //金额同步
        updateObj.setDebtTotal(updateObj.getTotalAmount()-updateReqVO.getReceivedFare());
        updateObj.setNotPoint(updateObj.getCustomerRebate()-updateReqVO.getIsPoint());
        updateObj.setNotWriteOff(updateObj.getWriteExpenses()-updateReqVO.getIsWriteOff());
        dpMapper.updateById(updateObj);
        updateDpItemList(updateReqVO.getId(), updateReqVO.getDpItems());
        dpWestListMapper.deleteByNo(updateReqVO.getId());
        createDpEastList(updateReqVO.getId(), updateReqVO.getDpEastLists());
        dpEastListMapper.deleteByNo(updateReqVO.getId());
        createDpWestList(updateReqVO.getId(), updateReqVO.getDpWestLists());
        //修改对应仓库制单数据
        Integer storeType;
        DispatchVehicleDO vehicleDO = dispatchVehicleMapper.selectOne(
                new LambdaQueryWrapper<DispatchVehicleDO>()
                        .eq(DispatchVehicleDO::getDpId, id)
                        .orderByDesc(DispatchVehicleDO::getId)
                        .last("limit 1"));
        if (vehicleDO == null){
            updateReqVO.setRemCount(updateReqVO.getInCount());
            updateReqVO.setRemVolume(updateReqVO.getInVolume());
            updateReqVO.setRemWeight(updateReqVO.getWeight());
            storeType = updateReqVO.getStoreType();
        } else {
            storeType = vehicleDO.getDest();
        }
        updateReqVO.setStatus(1);
        updateDpByStoreType(storeType,updateReqVO);
    }

    private void updateDpByStoreType(Integer StoreType, DpSaveReqVO updateReqVO){
        // 根据前仓库类型修改
        if (StoreType == 1) {
            DpYwDO updateObjYw = BeanUtils.toBean(updateReqVO, DpYwDO.class);
            dpYwMapper.updateById(updateObjYw);
        } else if (StoreType == 2) {
            DpGzDO updateObjGz = BeanUtils.toBean(updateReqVO, DpGzDO.class);
            dpGzMapper.updateById(updateObjGz);
        } else if (StoreType == 3) {
            DpDnDO updateObjDn = BeanUtils.toBean(updateReqVO, DpDnDO.class);
            dpDnMapper.updateById(updateObjDn);
        } else if (StoreType == 4) {
            DpWlmqDO updateObjWlmq = BeanUtils.toBean(updateReqVO, DpWlmqDO.class);
            dpWlmqMapper.updateById(updateObjWlmq);
        } else if (StoreType == 5) {
            DpNjDO updateObjNj = BeanUtils.toBean(updateReqVO, DpNjDO.class);
            dpNjMapper.updateById(updateObjNj);
        } else if (StoreType == 6) {
            DpBjDO updateObjBj = BeanUtils.toBean(updateReqVO, DpBjDO.class);
            dpBjMapper.updateById(updateObjBj);
        } else if (StoreType == 7) {
            DpDxDO updateObjDx = BeanUtils.toBean(updateReqVO, DpDxDO.class);
            dpDxMapper.updateById(updateObjDx);
        } else if (StoreType == 8) {
            DpAlmtDO updateObjDx = BeanUtils.toBean(updateReqVO, DpAlmtDO.class);
            dpAlmtMapper.updateById(updateObjDx);
        } else if (StoreType == 9) {
            DpBiskDO updateObjDx = BeanUtils.toBean(updateReqVO, DpBiskDO.class);
            dpBiskMapper.updateById(updateObjDx);
        } else if (StoreType == 10) {
            DpWslDO updateObjDx = BeanUtils.toBean(updateReqVO, DpWslDO.class);
            dpWslMapper.updateById(updateObjDx);
        } else if (StoreType == 11) {
            DpMskDO updateObjDx = BeanUtils.toBean(updateReqVO, DpMskDO.class);
            dpMskMapper.updateById(updateObjDx);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDp(String id) {
        // 删除主表
        dpMapper.deleteById(id);
        deleteDpItemByNo(id);
    }

    @Override
    public DpDO getDp(String id) {
        return dpMapper.selectById(id);
    }

    @Override
    public PageResult<DpDO> getDpPage(DpPageReqVO pageReqVO) {
        PageResult<DpDO> dpDOPageResult;
        Integer status = pageReqVO.getStatus();
        Integer exportStatus = pageReqVO.getExportStatus();
        if (exportStatus != null && exportStatus == 1){
            if(status==null||status!=2){
                return dpMapper.selectPage(pageReqVO);
            }else{
                return dpMapper.selectReturnPage(pageReqVO);
            }
        }
        if (status == null){
            dpDOPageResult = dpMapper.selectPage(pageReqVO);
        } else if (status == 2){
            return dpMapper.selectReturnPage(pageReqVO);
        }else {
            dpDOPageResult = dpMapper.selectPage(pageReqVO);
        }
        Long total = dpDOPageResult.getTotal();
        List<DpDO> list = dpDOPageResult.getList();
        List<String> dpIds = list.stream().map(DpDO::getId).collect(Collectors.toList());
        List<DispatchVehicleDO> allDispatchVehicles = dispatchVehicleMapper.selectByDispatchByIds(pageReqVO.getLine(), dpIds);
        Map<String, List<DispatchVehicleDO>> dpIdToVehiclesMap = allDispatchVehicles.stream().collect(Collectors.groupingBy(DispatchVehicleDO::getDpId));
        for (DpDO dpDO : list) {
            List<DispatchVehicleDO> vehicleList = dpIdToVehiclesMap.getOrDefault(dpDO.getId(), Collections.emptyList());
            String addressDetail = null, addressTime = null; Integer count = 0;
            for (DispatchVehicleDO dispatchVehicleDO : vehicleList) {
                JSONObject jsonObject = JSONObject.parseObject(dispatchVehicleDO.getDpData());
                if (jsonObject != null && jsonObject.get("outCount") == jsonObject.get("inCount")) {
                    count = (Integer) jsonObject.get("outCount");
                    String linedetails = dispatchVehicleDO.getLineDetails();
                    if (linedetails != null && !linedetails.equals("")) {
                        String[] lineDetails = dispatchVehicleDO.getLineDetails().split(",");
                        addressDetail = lineDetails[lineDetails.length - 1];
                    }
                    String addressCreateTimes = dispatchVehicleDO.getAddressCreateTimes();
                    if (addressCreateTimes != null && !addressCreateTimes.equals("")) {
                        String[] addressCreateTime = dispatchVehicleDO.getAddressCreateTimes().split(",");
                        addressTime = addressCreateTime[addressCreateTime.length - 1];
                    }
                    break;
                }
            }
            dpDO.setAddressTime(addressTime);
            dpDO.setAddressDetail(addressDetail);
            dpDO.setDpCount(count);
        }
        return new PageResult<>(list, total);
    }

    @Override
    public PageResult<DpDO> selectByShipper(DpPageReqVO pageReqVO) {
        return dpMapper.selectByShipper(pageReqVO);
    }

    @Override
    public PageResult<DpDO> shipperDate(DpPageReqVO pageReqVO) {
        PageResult<DpDO> dpDOPageResult= dpMapper.shipperDate(pageReqVO);
        Long total = dpDOPageResult.getTotal();
        List<DpDO> list = dpDOPageResult.getList();
        return new PageResult<>(list, total);
    }

    @Override
    public DpDO getDpFareCount(String shipper) {
        return dpMapper.getDpFareCount(shipper);
    }

    /**
     * ERP总物流单据审核
     * @param pageReqVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examineDp(DpPageReqVO pageReqVO) {
        List<DpDO> dpList = new ArrayList<>();
        Integer status = pageReqVO.getStatus();
        List<String> ids = pageReqVO.getIds();
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < ids.size(); i++) {
            DpDO dpDo = new DpDO();
            dpDo.setId(ids.get(i));
            dpDo.setStatus(status);
            dpDo.setUpdateTime(now);
            dpList.add(dpDo);
        }
        dpMapper.updateBatch(dpList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dpReturn(String id) {
        DpDO dpDO = dpMapper.selectById(id);
        Integer arrStoreType = 0;
        List<DispatchVehicleDO> dispList = dispatchVehicleMapper.selectListByDpId(id);
        int size = dispList.size();
        if (size == 0) {
            arrStoreType = dpDO.getStoreType();
        } else if (size == 1) {
            DispatchVehicleDO vehicleDO = dispList.get(0);
            Integer inventoryStatus = vehicleDO.getInventoryStatus();
            if (inventoryStatus == 1) {
                arrStoreType = dpDO.getStoreType();
            } else if (inventoryStatus == 2) {
                arrStoreType = vehicleDO.getDest();
            }
        } else {
            DispatchVehicleDO vehicleDO = dispList.get(0);
            Integer inventoryStatus = vehicleDO.getInventoryStatus();
            if (inventoryStatus == 1) {
                arrStoreType = dispList.get(1).getDest();
            } else if (inventoryStatus == 2) {
                arrStoreType = vehicleDO.getDest();
            }
        }
        DpDO homoStore = new DpDO();
        homoStore.setId(id);
        homoStore.setStatus(0);
        if (arrStoreType == 1) {
            DpYwDO bean = BeanUtils.toBean(homoStore, DpYwDO.class);
            dpYwMapper.updateById(bean);
        }else if (arrStoreType == 2) {
            dpGzMapper.updateById(BeanUtils.toBean(homoStore, DpGzDO.class));
        }else if (arrStoreType == 3) {
            dpDnMapper.updateById(BeanUtils.toBean(homoStore, DpDnDO.class));
        }else if (arrStoreType == 4) {
            dpWlmqMapper.updateById(BeanUtils.toBean(homoStore, DpWlmqDO.class));
        }else if (arrStoreType == 5) {
            dpNjMapper.updateById(BeanUtils.toBean(homoStore, DpNjDO.class));
        }else if (arrStoreType == 6) {
            dpBjMapper.updateById(BeanUtils.toBean(homoStore, DpBjDO.class));
        }else if (arrStoreType == 7) {
            dpDxMapper.updateById(BeanUtils.toBean(homoStore, DpDxDO.class));
        }
        dpMapper.deleteById(id);
        dpItemMapper.deleteByNo(id);
    }

    // ==================== 子表（总东线清单） ====================

    @Override
    public List<DpEastListDO> getDpEastListListByNo(String no) {
        return dpEastListMapper.selectListByNo(no);
    }


    // ==================== 子表（总西线清单） ====================

    @Override
    public List<DpWestListDO> getDpWestListListByNo(String no) {
        return dpWestListMapper.selectListByNo(no);
    }

    // ==================== 子表（ERP总制单货号详情） ====================

    @Override
    public List<DpItemDO> getDpItemListByNo(String no) {
        return dpItemMapper.selectListByNo(no);
    }

    @Override
    public DpCountQuantity getDpCountQuantity() {
        // 当前日期
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 今天的开始和结束时间
        LocalDateTime startOfDay = now.toLocalDate().atStartOfDay();
        String startOfDayFormatted = startOfDay.format(formatter);
        // 查询今天的总重量
        Double todayReceiving = dpMapper.getTotalWeightByTimeRange(startOfDayFormatted, startOfDayFormatted);

        // 本月的开始和结束时间
        // 本月的开始时间：获取本月的第一天，然后转换为 LocalDate，再调用 atStartOfDay()
        LocalDateTime startOfMonth = now.toLocalDate().withDayOfMonth(1).atStartOfDay();
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1).minusSeconds(1);
        String startOfMonthFormatted = startOfMonth.format(formatter);
        String endOfMonthFormatted = endOfMonth.format(formatter);
        // 查询本月的总重量
        Double monthReceiving = dpMapper.getTotalWeightByTimeRange(startOfMonthFormatted, endOfMonthFormatted);

        // 本年的开始和结束时间
        LocalDateTime startOfYear = now.toLocalDate().withMonth(1).withDayOfMonth(1).atStartOfDay();
        LocalDateTime endOfYear = startOfYear.plusYears(1).minusSeconds(1);
        String startOfYearFormatted = startOfYear.format(formatter);
        String endOfYearFormatted = endOfYear.format(formatter);
        // 查询本年的总重量
        Double yearReceiving = dpMapper.getTotalWeightByTimeRange(startOfYearFormatted, endOfYearFormatted);
        //查询本年的欠款金额
        Double yearOfDebtTotal = dpMapper.getDebtTotalForYear(startOfYearFormatted);
        //当日到货重量
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = startOfDay.format(fmt);
        String endTime = startOfDay.plusDays(1).minusSeconds(1).format(fmt);
        Double todayArriveWeight = dispatchVehicleMapper.getTotalWeightByTimeRange(startTime,endTime);
        //超出一个月未出货客户
//        Integer aMonthNotShip = dpMapper.getMonthNotShip(startOfMonthFormatted);
        Integer aMonthNotShip = dpMapper.getMaxship(startOfMonthFormatted)-dpMapper.getMinShip(startOfMonthFormatted);

        // 查询本月新增客户数量
        Integer newCustomer = dpMapper.getNewCustomerCount(startOfMonthFormatted);

        // 创建 DpCountQuantity 实体并返回
        DpCountQuantity result = new DpCountQuantity();
        result.setTodayReceiving(todayReceiving == null ? 0 : todayReceiving);
        result.setMonthReceiving(monthReceiving == null ? 0 : monthReceiving);
        result.setYearReceiving(yearReceiving == null ? 0 : yearReceiving);
        result.setNewCustomer(newCustomer);
        result.setYearOfDebtTotal(yearOfDebtTotal == null ? 0 : yearOfDebtTotal);
        result.setTodayArriveWeight(todayArriveWeight == null ? 0 : todayArriveWeight);
        result.setMonthNotShip(aMonthNotShip == null ? 0 : aMonthNotShip);
        //计算各收款金额
        List<BankStatementDO> bankStatementDOS = bankStatementMapper.selectDayReceiveMoney();
        //计算人民币
        BankStatementDO bankStatementRmbDO = sumMoneyByList(bankStatementDOS, 1);
        result.setDayReceiveRmbSum(bankStatementRmbDO.getDayPaymentSum());
        //计算美元
        BankStatementDO bankStatementDollarDO = sumMoneyByList(bankStatementDOS, 2);
        result.setDayReceiveDollarSum(bankStatementDollarDO.getDayPaymentSum());
        //计算人坚戈
        BankStatementDO bankStatementTengeDO = sumMoneyByList(bankStatementDOS, 3);
        result.setDayReceiveTengeSum(bankStatementTengeDO.getDayPaymentSum());
        //计算卢布
        BankStatementDO bankStatementRubleDO = sumMoneyByList(bankStatementDOS, 4);
        result.setDayReceiveRubleSum(bankStatementRubleDO.getDayPaymentSum());
        return result;
    }

    private BankStatementDO sumMoneyByList(List<BankStatementDO> list, Integer currencyType) {
        list = list.stream()
                .filter(bankStatement -> bankStatement.getCurrencyType() == currencyType)
                .collect(Collectors.toList());
        // 计算字段总和
        Double dayPaymentSum = list.stream()
                .mapToDouble(BankStatementDO::getDayPayment).sum();
        BankStatementDO bankStatementDO = new BankStatementDO();
        bankStatementDO.setDayPaymentSum(dayPaymentSum);
        return bankStatementDO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer dpPickUp(String tableName, String id, Integer pickStatus,Integer signNum,Integer signStatus) {
        DpDO dpDO= dpMapper.selectDpByid(tableName,id);
        String xx=dpDO.getId();
        dpDO.setId(null);
        DpSignDO dpSignDO=BeanUtils.toBean(dpDO, DpSignDO.class);
        dpSignDO.setDpId(xx);
        dpSignDO.setSignStatus(signStatus);
        if(tableName.equals("erp_dp_almt")){
            dpSignDO.setStoreType(8);
        }else if(tableName.equals("erp_dp_bisk")){
            dpSignDO.setStoreType(9);
        } else if (tableName.equals("erp_dp_wsl")) {
            dpSignDO.setStoreType(10);
        } else if (tableName.equals("erp_dp_msk")) {
            dpSignDO.setStoreType(11);
        }
        dpSignDO.setSignNum(signNum-dpSignDO.getSignNum());
        dpSignMapper.insert(dpSignDO);
        if(signStatus == 2){
            dispatchVehicleMapper.deleteDispById(id,1);
            return dpMapper.updateArrStatusBytableName(tableName, id, pickStatus,signNum,2);
        }else {
            return dpMapper.updatePickStatusBytableName(tableName, id, pickStatus,signNum);
        }
    }

    private void updateDpItemList(String no, List<DpItemDO> list) {
        deleteDpItemByNo(no);
        createDpItemList(no, list);
    }

    private void deleteDpItemByNo(String no) {
        dpItemMapper.deleteByNo(no);
    }

    @Override
    public List<DpDO> searchSipperDpList(String shipper, String no, Integer prepaidStatus) {
        if(no!=null){
            String[] result = no.split(",");
            return dpMapper.searchSipperDpList(shipper, result, prepaidStatus);
        }else {
            return dpMapper.searchSipperDpList(shipper,null, prepaidStatus);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dpPay(PayDO payDO) {
        payMapper.insert(payDO);
        Gson gson = new Gson();
        JsonArray jsonArray=gson.fromJson(payDO.getPayIdAmount(),JsonArray.class);
        for (int i = 0; i < jsonArray.size(); i++) {
           dpMapper.dpPay(jsonArray.get(i).getAsJsonObject().get("amount").getAsDouble(),jsonArray.get(i).getAsJsonObject().get("id").getAsString());
        }
    }

    public void arrDataDpUpdata(String id, Integer outCount, Double outVolume, Double outWeight) {
        DpDO dpDO = dpMapper.selectById(id);
        dpDO.setArrCount(outCount + dpDO.getArrCount());
        dpDO.setArrVolume(outVolume + dpDO.getArrVolume());
        dpDO.setArrWeight(outWeight + dpDO.getArrWeight());
        dpDO.setArrivedTime(LocalDateTime.now());
//        Integer calmethod = dpDO.getCalmethod();
//        Double debt_total = 0.00;
//        if (calmethod == 1) {
//            debt_total = outWeight * dpDO.getUnitPrice();
//        } else if (calmethod == 2) {
//            debt_total = outVolume * dpDO.getCubeUnitPrice();
//        } else if (calmethod == 3) {
//            debt_total = dpDO.getUnitPrice();
//        } else if (calmethod == 4) {
//            debt_total = outWeight * dpDO.getUnitPrice() + outVolume * dpDO.getCubeUnitPrice();
//        }
//        dpDO.setDebtTotal(dpDO.getDebtTotal() + debt_total);
        dpMapper.updateById(dpDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dpClaim(ClaimDO claimDO) {
        claimMapper.insert(claimDO);
        Gson gson = new Gson();
        JsonArray jsonArray=gson.fromJson(claimDO.getClaimIdAmount(),JsonArray.class);
        for (int i = 0; i < jsonArray.size(); i++) {
            dpMapper.dpClaim(jsonArray.get(i).getAsJsonObject().get("amount").getAsDouble(),jsonArray.get(i).getAsJsonObject().get("id").getAsString());
        }
    }

    @Override
    public List<DpDO> getNoByShipper(String shipper) {
        return dpMapper.getNoByShipper(shipper);
    }

        //自动分配后不需要此逻辑
        // 按 shipper 分组
//        Map<String, List<DpDO>> groupedMap = list.stream()
//                .filter(dp -> dp.getShipper() != null) // 过滤掉 null 值
//                .collect(Collectors.groupingBy(DpDO::getShipper));
//        // 构造结果列表
//        List<DpDO> result = new ArrayList<>();
//        for (Map.Entry<String, List<DpDO>> entry : groupedMap.entrySet()) {
//            DpDO parentDp = new DpDO();
//            parentDp.setShipper(entry.getKey()); // 设置 shipper
//            parentDp.setChildren(entry.getValue()); // 设置子列表
//            result.add(parentDp);
//        }


    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public Boolean importUserList(Integer storeType, List<DpIdImportExcelVO> importDpIds, Boolean isUpdateSupport) {
        if (CollUtil.isEmpty(importDpIds)) {
            throw exception(DPIDS_IMPORT_LIST_IS_EMPTY);
        }
        List<String> ids = importDpIds.stream()
                .map(DpIdImportExcelVO::getId)
                .filter(Objects::nonNull) // 过滤掉 null 值
                .collect(Collectors.toList());
        List<String> notExistIds;
        boolean a = true;
        boolean b = false;
        if (storeType == 1) {
            notExistIds = dpYwMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpYwMapper.insertBatch(BeanUtils.toBean(list, DpYwDO.class));
            }
        } else if (storeType == 2) {
            notExistIds = dpGzMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpGzMapper.insertBatch(BeanUtils.toBean(list, DpGzDO.class));
            }
        } else if (storeType == 3) {
            notExistIds = dpWlmqMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpWlmqMapper.insertBatch(BeanUtils.toBean(list, DpWlmqDO.class));
            }
        } else if (storeType == 4) {
            notExistIds = dpDnMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpDnMapper.insertBatch(BeanUtils.toBean(list, DpDnDO.class));
            }
        } else if (storeType == 5) {
            notExistIds = dpNjMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpNjMapper.insertBatch(BeanUtils.toBean(list, DpNjDO.class));
            }
        } else if (storeType == 6) {
            notExistIds = dpBjMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpBjMapper.insertBatch(BeanUtils.toBean(list, DpBjDO.class));
            }
        } else if (storeType == 7) {
            notExistIds = dpDxMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpDxMapper.insertBatch(BeanUtils.toBean(list, DpDxDO.class));
            }
        } else if (storeType == 8) {
            notExistIds = dpAlmtMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpAlmtMapper.insertBatch(BeanUtils.toBean(list, DpAlmtDO.class));
            }
        } else if (storeType == 9) {
            notExistIds = dpBiskMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                // 获取该仓库不存在的单据
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpBiskMapper.insertBatch(BeanUtils.toBean(list, DpBiskDO.class));
            }
        } else if (storeType == 10) {
            notExistIds = dpWslMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpWslMapper.insertBatch(BeanUtils.toBean(list, DpWslDO.class));
            }
        } else if (storeType == 11) {
            notExistIds = dpMskMapper.getNotExistIds(ids);
            if (notExistIds.size() > 0) {
                List<DpDO> list = dpMapper.selectList(new LambdaQueryWrapper<DpDO>()
                        .in(DpDO::getId, notExistIds)).stream().collect(Collectors.toList());
                return dpMskMapper.insertBatch(BeanUtils.toBean(list, DpMskDO.class));
            }
        } else {
            return b;
        }
        return a;
    }

    public List dpUpateNo(List<DpImportExcelVO> list,String id,Integer storeType,Integer line){
        int x= Integer.parseInt(id.substring(id.length() - 4));
        for (int i = 0; i < list.size(); i++) {
            int y=x+i;
            if(storeType==4){
                list.get(i).setId(id.substring(0, 12)+String.format("%04d", y));
            }else {
                list.get(i).setId(id.substring(0, 10)+String.format("%04d", y));
            }
            list.get(i).setDeleted(true);
            list.get(i).setStoreType(storeType);
            list.get(i).setLine(line);
            list.get(i).setRemCount(list.get(i).getInCount());
            list.get(i).setRemWeight(list.get(i).getWeight());
            list.get(i).setRemVolume(list.get(i).getInVolume());

            if(list.get(i).getGuaranteedRate()!=null&&list.get(i).getGoodsValue()!=null){
                list.get(i).setPremium(list.get(i).getGuaranteedRate()*list.get(i).getGoodsValue()/100);
            }
            if(list.get(i).getTotalAmount()==null){
                double money=list.get(i).getAdvancePayPack()+list.get(i).getAdvancePayPackUp()+list.get(i).getAdvancePayForGoods()+list.get(i).getAdvancePayChinaFreight()+list.get(i).getPremium()+list.get(i).getCollecting()-list.get(i).getDiscountAmount();
                if(list.get(i).getCalmethod()==1){
                    list.get(i).setTotalAmount((double) Math.round(list.get(i).getWeight()*list.get(i).getUnitPrice()+money));
                } else if (list.get(i).getCalmethod()==2) {
                    list.get(i).setTotalAmount((double) Math.round(list.get(i).getInVolume()*list.get(i).getCubeUnitPrice()+money));
                } else if (list.get(i).getCalmethod()==3) {
                    list.get(i).setTotalAmount((double) Math.round(list.get(i).getUnitPrice()+money));
                } else if (list.get(i).getCalmethod()==4) {
                    list.get(i).setTotalAmount((double) Math.round(list.get(i).getInVolume()*list.get(i).getCubeUnitPrice()+money+list.get(i).getWeight()*list.get(i).getUnitPrice()));
                }
            }
            if (list.get(i).getDensity()==null) {
                list.get(i).setDensity((double) Math.round(list.get(i).getWeight()/list.get(i).getInVolume()));

            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public Boolean importDpList(Integer storeType,Integer line, List<DpImportExcelVO> list, Boolean isUpdateSupport) {

        if (storeType==1) {
            String id= giYwService.generateOrderNumber();
            giYwMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiYwDO.class));
            return dpYwMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpYwDO.class));
        }else if (storeType==2) {
            String id= giGzService.generateOrderNumber();
            giGzMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiGzDO.class));
            return dpGzMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpGzDO.class));
        }else if (storeType==3) {
            String id= giDnService.generateOrderNumber();
            giDnMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiDnDO.class));
            return dpDnMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpDnDO.class));
        }else if (storeType==4) {
            String id= giWlmqService.generateOrderNumber();
            giWlmqMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiWlmqDO.class));
            return dpWlmqMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpWlmqDO.class));
        }else if (storeType==5) {
            String id= giNjService.generateOrderNumber();
            giNjMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiNjDO.class));
            return dpNjMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpNjDO.class));
        }else if (storeType==6) {
            String id= giBjService.generateOrderNumber();
            giBjMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiBjDO.class));
            return dpBjMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpBjDO.class));
        }else if (storeType==7) {
            String id= giDxService.generateOrderNumber();
            giDxMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), GiDxDO.class));
            return dpDxMapper.insertBatch(BeanUtils.toBean(dpUpateNo(list,id,storeType,line), DpDxDO.class));
        }else{
            return false;
        }

    }

    @Override
    public List<DpOutStoreRespVo> selectDpByids(Integer storeType, List<String> ids) {
        List<DpDO> dpDOS = new ArrayList<>();
        if (storeType == 1) {
            List<DpYwDO> list = dpYwMapper.selectList(new LambdaQueryWrapper<DpYwDO>().in(DpYwDO::getId, ids).orderByDesc(DpYwDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 2) {
            List<DpGzDO> list = dpGzMapper.selectList(new LambdaQueryWrapper<DpGzDO>().in(DpGzDO::getId, ids).orderByDesc(DpGzDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 3) {
            List<DpDnDO> list = dpDnMapper.selectList(new LambdaQueryWrapper<DpDnDO>().in(DpDnDO::getId, ids).orderByDesc(DpDnDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 4) {
            List<DpWlmqDO> list = dpWlmqMapper.selectList(new LambdaQueryWrapper<DpWlmqDO>().in(DpWlmqDO::getId, ids).orderByDesc(DpWlmqDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 5) {
            List<DpNjDO> list = dpNjMapper.selectList(new LambdaQueryWrapper<DpNjDO>().in(DpNjDO::getId, ids).orderByDesc(DpNjDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 6) {
            List<DpBjDO> list = dpBjMapper.selectList(new LambdaQueryWrapper<DpBjDO>().in(DpBjDO::getId, ids).orderByDesc(DpBjDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 7) {
            List<DpDxDO> list = dpDxMapper.selectList(new LambdaQueryWrapper<DpDxDO>().in(DpDxDO::getId, ids).orderByDesc(DpDxDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 8) {
            List<DpAlmtDO> list = dpAlmtMapper.selectList(new LambdaQueryWrapper<DpAlmtDO>().in(DpAlmtDO::getId, ids).orderByDesc(DpAlmtDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 9) {
            List<DpBiskDO> list = dpBiskMapper.selectList(new LambdaQueryWrapper<DpBiskDO>().in(DpBiskDO::getId, ids).orderByDesc(DpBiskDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 10) {
            List<DpWslDO> list = dpWslMapper.selectList(new LambdaQueryWrapper<DpWslDO>().in(DpWslDO::getId, ids).orderByDesc(DpWslDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else if (storeType == 11) {
            List<DpMskDO> list = dpMskMapper.selectList(new LambdaQueryWrapper<DpMskDO>().in(DpMskDO::getId, ids).orderByDesc(DpMskDO::getId));
            dpDOS = BeanUtils.toBean(list, DpDO.class);
        } else {
        }
        return BeanUtils.toBean(dpDOS, DpOutStoreRespVo.class);
    }

}
